<template>
    <div>
        <p style="font-size: 25px;font-weight: bold;margin-left: 700px;margin-top: 40px">服务管理</p>
      <!-- 添加服务按钮 -->
      <el-button @click="add" style="margin-top: 50px;">添加</el-button>
  
      <!-- 服务列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="service_type" label="服务类型" />
        <el-table-column prop="pay_type" label="付款方式" />
        <el-table-column prop="services_prices" label="服务和价格" >
          <template #default="scope">
          <div v-for="(price, index) in scope.row.services_prices" :key="index">
              <p>服务名称：{{ price.name }}</p>
              <p>服务单价：{{ price.unitPrice }}</p>
              <p>市场价：{{ price.marketPrice }}</p>
      </div>
    </template>
  </el-table-column>
        <el-table-column prop="main_image" label="服务主图">
          <template #default="scope">
            <img :src="scope.row.main_image" alt="服务主图" style="width: 50px; height: 50px;">
          </template>
        </el-table-column>
        <el-table-column prop="detail_images" label="服务详情">
          <template #default="scope">
            
              <img :src="scope.row.detail_images" alt="服务详情" style="width: 50px; height: 50px;">
            
          </template>
        </el-table-column>
        <el-table-column prop="service_chra" label="服务特点" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="editData(scope.row)">编辑</el-button>
            <el-button @click="delData(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="query.page"
        v-model:page-size="query.pagesize"
        :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  
      <!-- 添加/编辑对话框 -->
      <el-dialog v-model="dialogVisible" title="服务信息">
        <el-form :model="form">
          <el-form-item label="服务类型" :label-width="formLabelWidth">
            <el-select v-model="form.service_type" placeholder="请选择服务类型">
              <el-option v-for="item in serviceTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="付款方式" :label-width="formLabelWidth">
            <el-radio-group v-model="form.pay_type">
              <el-radio v-for="item in payChoices" :key="item.value" :label="item.label" :value="item.value" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="服务和价格" :label-width="formLabelWidth">
            <el-button @click="addServicePrice">添加</el-button>
            <div v-for="(price, index) in form.services_prices" :key="index" class="service-price">
              <el-input v-model="price.name" placeholder="服务名称" style="width: 100px; display: inline-block;" />
              <el-input v-model="price.unitPrice" placeholder="服务单价" style="width: 100px; display: inline-block;" />
              <el-input v-model="price.marketPrice" placeholder="市场价" style="width: 100px; display: inline-block;" />
              <el-button @click="removeServicePrice(index)" type="danger">删除</el-button>
            </div>
          </el-form-item>
          <el-form-item label="服务主图" :label-width="formLabelWidth">
            <el-upload
              action="http://localhost:8000/uploads/main_images"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :file-list="form.main_image ? [{name: 'main_image', url: form.main_image}] : []"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="服务详情" :label-width="formLabelWidth">
            <el-upload
              action="http://localhost:8000/uploads/detail_images"
              list-type="picture-card"
              :limit="5"
              :on-exceed="handleExceed"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :file-list="form.detail_images"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="服务特点" :label-width="formLabelWidth">
            <el-input v-model="form.service_chra" maxlength="10" show-word-limit placeholder="不超过10个字，如：高温消杀" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import axios from 'axios';
  import config from '../api/config.js';
  
  const { serviceTypes, payChoices } = config;
  let dialogVisible = ref(false);
  const form = ref({
    service_type: '',
    pay_type: '',
    services_prices: [{ name: '', unitPrice: '', marketPrice: '' }],
    main_image: '',
    detail_images: [],
    service_chra: ''
  });
  
  const formLabelWidth = '120px';
  const query = ref({ page: 1, pagesize: 2 });
  const total = ref(0);
  
  const tableData = ref([]);
  
  const addServicePrice = () => {
    form.value.services_prices.push({ name: '', unitPrice: '', marketPrice: '' });
  };
  
  const removeServicePrice = (index) => {
    form.value.services_prices.splice(index, 1);
  };
  
  const getTableData = () => {
    axios.get(`http://127.0.0.1:8000/user/service/?page=${query.value.page}&size=${query.value.pagesize}`)
      .then((response) => {
        tableData.value = response.data.results;
        total.value = response.data.count;
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });
  };
  
  const handleSizeChange = (newSize) => {
    query.value.pagesize = newSize;
    getTableData();
  };
  
  const handleCurrentChange = (newPage) => {
    query.value.page = newPage;
    getTableData();
  };
  
  const editData = (row) => {
    form.value = { ...row };
    dialogVisible.value = true;
  };
  
  const add = () => {
    dialogVisible.value = true;
  };
  
  const submitForm = () => {
    console.log('Form submitted:', form.value);
    axios.post("http://127.0.0.1:8000/user/service/", form.value)
      .then(res => {
        console.log(res);
        if (res.status === 201) {
          ElMessage.success('添加成功');
          dialogVisible.value = false;
          form.value = {
            service_type: '',
            pay_type: '',
            services_prices: [{ name: '', unitPrice: '', marketPrice: '' }],
            main_image: '',
            detail_images: [],
            service_chra: ''
          };
          getTableData();
        }
      })
      .catch(error => {
        console.error('Error submitting form:', error);
        ElMessage.error('添加失败');
      });
  };
  
  const handlePictureCardPreview = (file) => {
  console.log('Preview:', file);
  };
  
  const handleRemove = (file, fileList) => {
  console.log('Remove:', file, fileList);
  };
  
  const handleExceed = (files, fileList) => {
  console.log('Exceed:', files, fileList);
  };
  
  getTableData();
  </script>
  
  <style scoped>
  .service-price {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  }
  </style>